package sample.util.txt;

import java.io.*;

/**
 * Created by 杨家兵 on 2016/12/8.
 */
public class FileOfTxtUtil {

    /**
     * 创建文件
     * @param fileName 文件名
     * @return
     */
    public static boolean creatFile(File fileName){
        boolean flag=false;
        try{
            if(!fileName.exists()){
                fileName.createNewFile();
                flag=true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 向TxT中写入数据
     * @param data 数据
     * @param name 文件名
     */
    public static void writeDataToTxt(String data,String name){
        BufferedWriter bw = null;
        try {
            OutputStream os = new FileOutputStream(name);
            bw = new BufferedWriter(new OutputStreamWriter(os));
            for (String value : data.split("\n"))
            {
                bw.write(value);
                bw.newLine();//换行
            }
        }
        catch (IOException e1){}
        finally
        {
            if (bw != null)
            {
                try
                {
                    bw.close();
                } catch (IOException e1){}
            }
        }
    }
    /**
     * 读取Txt中的数据
     * @param name 文件名
     * @return
     */
    public static String readDataToTxt(String name){
        BufferedReader br = null;
        StringBuilder txt=null;
        try {
            txt = new StringBuilder();
            br = new BufferedReader(new FileReader(name));
            String data = br.readLine();
            while(data!=null)
            {
                txt.append(data);
                // txt.append("\n");
                data = br.readLine();
            }

        } catch (FileNotFoundException ex) {

        } catch (IOException ex) {

        } finally {
            try {
                br.close();
            } catch (IOException ex) {

            }
        }
        return txt.toString();
    }
}
